<template>
	<div class="map_main">
		<div class="map_main_input" v-if="isMediaDevices">
			<div class="update_file_audio_list">
				<select>
					<option>请选择...</option>
					<option v-for="(item, index) in recorders" :value="index">{{item}}</option>
				</select>
			</div>
			<div class="update_file">
				<a href="javascript:;" @click="recorderStartClickHandle" v-if="recorderStatus !== 'RECORDER_START'">
					录音
				</a>
				<a href="javascript:;" @click="recorderStopClickHandle" v-if="recorderStatus === 'RECORDER_START'">
					停止录音
				</a>
			</div>
		</div>
		<div class="map_main_input on" v-if="!isMediaDevices">
			<div class="map_main_input_item">
				<input type="text" value="" placeholder="输入起点到终点" ref="busSearchInput">
			</div>
			<div class="map_main_input_item">
				<a href="javascript:;" @click="busSearchHandle">
					<i class="icon3 search"></i>
				</a>
			</div>
		</div>
		<div class="map_main_tip">搜索内容应包含"某地到某地"或"某地去某地"</div>
		<div class="update_file_audio"></div>
		<div class="map_main_view">
			<div class="baidumap" id="baidumap"></div>
		</div>
		<div class="baidumap_list">
			<div :class="'baidumap_list_item'+(index === 0 ? ' recon' : '')" v-for="(item, index) in maplist">
				<span>{{(index===0?'推荐':'')}}方案{{index+1}}</span>
				<span>{{item}}</span>				
			</div>
		</div>
		<Dialog :isShowDialog="isShowDialog" :className="dialogClassName">
			<div class="tip" slot="tip">
				<span>{{dialog_content}}</span>
				<a href="javascript:;" @click="closeClickHandle">Enter</a>
			</div>
		</Dialog>
	</div>
</template>
<script>
	import Axios from "axios";
	import HZRecorder from '../assets/recorder.js';
	class Recorder{
		constructor(){
			const that = this;
			that.dom = $("<audio></audio>").appendTo(".update_file_audio")[0];
			that.status = "RECORDER_STOP";
			that.isMediaDevices = navigator.mediaDevices;
			console.log(navigator.mediaDevices)
			return this;
		}
		start(){
			const that = this;
			if(navigator.mediaDevices){
				navigator.mediaDevices.getUserMedia({audio: true, video: false}).then((stream) => {
					that.recorder = new HZRecorder(stream);
					that.recorder.start();
					that.status = "RECORDER_START";
		        }).catch((err) => {
		        	console.log(err)
		        });
			}else{
				return {};
			}
			return this;
		}
		stop(){
			this.recorder && this.recorder.stop() && (this.status = "RECORDER_STOP");
			return this;
		}
		pause(){
			this.recorder && this.recorder.pause() && (this.status = "RECORDER_PAUSE");
			return this;
		}
		getWAVFile(){
			return this.recorder && this.recorder.getBlob();
		}
	}
	let recorder = new Recorder(),
		map = null;
	export default {
		name: 'map',
		data: function(){
			return {
				recorderStatus: "RECORDER_STOP",
				recorders:[],
				maplist:[],
				isShowDialog: false,
				dialogClassName: 'zoomIn',
				dialog_content: '',
				isMediaDevices: false
			}
		},
		components:{
			Dialog: r => require.ensure([], () => r(require('../components/dialog.vue')), 'groups_dialog')
		},
		mounted:function(){
			this.$set(this, "isMediaDevices", recorder.isMediaDevices);
			this.$emit("setDataObject", {type:"map", title:"城市公交查询", showTip:false})
			map = new BMap.Map("baidumap", {
			    mapStyle: {
			        styleJson:[{
			            "featureType": "all",
			            "elementType": "geometry",
			            "stylers": {
			                "hue": "#007fff",
			                "saturation": 89
			            }
			        }, {
			            "featureType": "water",
			            "elementType": "all",
			            "stylers": {
			                "color": "#ffffff"
			            }
			        }]
			    }
			});
			var point = new BMap.Point(116.331398, 39.897445);
			map.centerAndZoom(point, 12);

			var myCity = new BMap.LocalCity();
			myCity.get(function(res){
				console.log(res)
				map.setCenter(res.name);
				map.centerAndZoom(res.name, 11);
			});
		},
		watch:{
			recorders:function(){
				const that = this;
				let last = this.$data.recorders[this.$data.recorders.length-1];
				console.log(this.$data.recorders, last);
				if (!/到|去/.test(last)){
					return;
				}
				$.each('到 去'.split(' '), (i, item) => {
					last = (new RegExp(item)).test(last) ? last.split(item) : last;
					if ($.isArray(last) && last.length>1){
						return false;
					}
				});
				var start = last[0];
				var end = last[1];
				var routePolicy = [BMAP_TRANSIT_POLICY_LEAST_TIME,BMAP_TRANSIT_POLICY_LEAST_TRANSFER,BMAP_TRANSIT_POLICY_LEAST_WALKING,BMAP_TRANSIT_POLICY_AVOID_SUBWAYS];
				var transit = new BMap.TransitRoute(map, {
						renderOptions: {map: map},
						policy: 0
					});
				map.clearOverlays(); 
				search(start,end,routePolicy[0]); 
				function search(start,end,route){ 
					transit.setPolicy(route);
					transit.search(start,end);
				}
				var transit = new BMap.TransitRoute(map, {
					renderOptions: {
						map: map
					},
					onSearchComplete: function(result) {
						if (transit.getStatus() == BMAP_STATUS_SUCCESS) {
							var firstPlan = result.getPlan(0);

							// 绘制步行线路
							for (var i = 0; i < firstPlan.getNumRoutes(); i++) {
								var walk = firstPlan.getRoute(i);
								if (walk.getDistance(false) > 0) {
									// 步行线路有可能为0
									map.addOverlay(new BMap.Polyline(walk.getPath(), {
										lineColor: "green"
									}));
								}
							}
							// 绘制公交线路
							for (i = 0; i < firstPlan.getNumLines(); i++) {
								var line = firstPlan.getLine(i);
								map.addOverlay(new BMap.Polyline(line.getPath()));
							}
							// 输出方案信息
							var s = [];
							for (i = 0; i < result.getNumPlans(); i++) {
								s.push(result.getPlan(i).getDescription(false)+"。");
							}
							that.$set(that, "maplist", s);
						}
					}
				});
				transit.search(start, end);
			}
		},
		methods:{
			busSearchHandle:function(){
				let v = this.$refs.busSearchInput.value.replace(/^\s+|\s+$/gim,'');
				if (!/\s+/.test(v)){
					const recorders = $.extend([], this.$data.recorders);
					recorders.push(v)
					this.$set(this, "recorders", recorders);
				}
			},
			closeClickHandle(){
				this.$set(this, 'isShowDialog', false);
			},
			setPageType(v){
				this.setDataObject(v)
			},
			setDataObject(v){
				const that = this;
				$.extend(that.$data, v);
				console.log(that.$data)
			},
			recorderStartClickHandle(){
				const that = this;
				this.$nextTick(() => {
					that.$set(that, "recorderStatus", "RECORDER_START")
				})
				this.$nextTick(() => {
					recorder.start()
				})
			},
			recorderStopClickHandle(){
				const that = this;
				this.$nextTick(() => {
					that.$set(that, "recorderStatus", "RECORDER_STOP")
				})
				this.$nextTick(() => {
					recorder.stop();
					const result = recorder.getWAVFile();
					console.log(result)
					//let url = URL.createObjectURL(result);
					if (result){
						let formData = new FormData();
						formData.append('file', result, Date.parse(new Date())+".wav");
						formData.append('accept', 'client');
						formData.append('news_type', 'wav');
						Axios.post("//192.168.31.133:8083/aip", formData, {
							headers:{'Content-Type': 'multipart/form-data'}
						}).then((res) => {
							console.log(res)
							if (res.data.status === 1){
								const recorders = $.extend([], that.$data.recorders);
								recorders.push(res.data.data[0])
								that.$set(that, "recorders", recorders);
							}
						}).catch((err) => {
							console.log(err)
						})
					}
				})
			}
		}
	}
</script>
<style lang="less">
	@base:23.44/1rem;
	.map_main{
		min-height: 0/@base;
		margin:70/@base 0 0;
		padding:0 0 70/@base 0;
		.map_main_input{
			display:flex;
			&.on{
				.map_main_input_item{
					width:90%;
					background-color: #fff;
					input{
						width: 90%;
						padding:20/@base 18/@base;
						font-size: 20/@base;
						border:0;
					}
					&:last-child{
						width:15%;
						text-align: center;
						a{
							padding:14/@base 18/@base;
							text-decoration: none;
							display: block;
							color:#333;
						}
					}
				}
			}
			.update_file{
				width:30%;
				background-color: #fff;
				display:flex;
				a{
					width:100%;
					display: block;
					text-align: center;
					text-decoration: none;
					line-height: 70/@base;
					color:#333;
				}
			}
			.update_file_audio_list{
				width:70%;
				background-color: #fff;
				span{
					display:block;
				}
				select{
					width:100%;
					padding:20/@base;
					font-size:20/@base;
				}
			}
		}
		.map_main_tip{
			font-size: 20/@base;
			text-align: center;
			padding:10/@base 0;
			background-color: #fafad2;
		}
		.map_main_view{
			.baidumap{
				width:100%;
				height:0/@base;
			}
		}
		.baidumap_list{
			.baidumap_list_item{
				background-color: #fff;
				margin:10/@base 0;
				padding:50/@base 20/@base 20/@base 20/@base;
				font-size: 20/@base;
				text-indent: 40/@base;
				line-height: 30/@base;
				position: relative;
				&.recon{
					background-color: #fafad2;
					min-height: 300/@base;
				}
				&:first-child{
					padding-top:70/@base;
					span{
						&:first-child{
							color:#999;
							top:20/@base;
						}
					}
				}
				span{
					display:block;
					&:first-child{
						text-indent:0;
						font-weight: 700;
						color:#ccc;
						padding:10/@base 0;
						position: absolute;
						top:0;
						left:20/@base;
					}
				}
			}
		}
	}
</style>